'''
@Author: your name
@Date: 2020-02-05 15:47:08
@LastEditTime : 2020-02-05 16:25:59
@LastEditors  : Please set LastEditors
@Description: In User Settings Edit
@FilePath: \pyqt5\demo_093_右键菜单.py
'''
from PyQt5.Qt import *


class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('demo_093_右键菜单')
        self.resize(500, 500)
        self.setup_ui()

    def setup_ui(self):
        #self.右键菜单()
        pass

    def contextMenuTest(self, point: QPoint):
        menu_file = self.customerContextMenu()
        dest_point=self.mapToGlobal(point)
        menu_file.exec_(dest_point)
        #menu_file.exec_(point)

    def customerContextMenu(self):
        btn = QPushButton('File',self)
        menu_file = QMenu(btn)

        new_action = QAction('&New', menu_file)
        new_action.setIcon(QIcon('ico/orange.ico'))
        menu_file.addAction(new_action)
        new_action.triggered.connect(lambda: print('新建按钮被按下了'))

        open_action = QAction('&Open', menu_file)
        open_action.setIcon(QIcon('ico/open.ico'))
        menu_file.addAction(open_action)
        open_action.triggered.connect(lambda: print('打开按钮被按下了'))

        menu_file.addSeparator()

        open_recent_menu = QMenu(menu_file)
        open_recent_menu.setTitle('open recent..')
        file_action = QAction('PyQt-Gui编程.py', open_recent_menu)
        open_recent_menu.addAction(file_action)

        menu_file.addMenu(open_recent_menu)
        menu_file.addSeparator()


        exit_action = QAction('&Exit',menu_file)
        exit_action.setIcon(QIcon('ico/delete.ico'))
        menu_file.addAction(exit_action)
        exit_action.triggered.connect(lambda : print('退出按钮被按下了'))


        btn.setMenu(menu_file)
        
        return menu_file
# method 1 overwrite  this method 
    # def contextMenuEvent(self,evt):
    #     menu_file = self.模拟菜单()
    #     menu_file.exec_(evt.globalPos())


if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)

    win = Window()
#method 2 
    win.setContextMenuPolicy(Qt.CustomContextMenu)
    win.customContextMenuRequested.connect(win.contextMenuTest)

    win.show()
    sys.exit(app.exec_())
